<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\common\model\UrlModel;
use app\common\model\NewsModel;
use app\common\model\SettingModel;
use app\common\model\MessagesModel;
use app\common\model\DingdingModel;     //钉钉消息通知
use app\index\controller\UserAgent_C;
use think\facade\Session;
use think\facade\View;
use useragent\useragent;    //获取客户端系统、浏览器信息
use PHPMailer\PHPMailer\PHPMailer;      //评论邮件通知
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

class Messages extends Common
{
    public function getList(){
        $admin_id = Session::get('admin_id');
        if(empty($admin_id)){
            return json(['code'=>1, 'msg'=>'请先登录','data'=>[]]);
        }
        
        $keyword = input('keyword');
        $map = [];
        if(!empty($keyword)){
            $map[] = ['nickname|mail','like','%'.$keyword.'%'];
        }
        $list = MessagesModel::pageList($map);
	        foreach($list as $key=>$val){
	        $val->pidions = NewsModel::where('id',$val->pid)->value('title');
	        $val->titlemes = MessagesModel::where('id',$val->pcode)->value('nickname');
	        $val->pidnewsid = UrlModel::getShowUrl($val->pid).'.html#'.$val->id.'';
	}

        return json(['code'=>0,'msg'=>'success','data'=>$list]);
    }

    public function del(){
        $admin_id = Session::get('admin_id');
        if(empty($admin_id)){
            return json(['code'=>1, 'msg'=>'请先登录','data'=>[]]);
        }
        
        $id = $this->request->param('ids');
        $res = MessagesModel::destroy($id,true);
        if($res){
            return json(['code'=>0,'msg'=>'删除成功']);
        }else{
            return json(['code'=>1,'msg'=>'删除失败']);
        }
    }
    
    public function e_mail($mailId,$mailContact){
        $config = SettingModel::where('group','zh')->column('value','name');//获取信息
        $info   = MessagesModel::info($mailId);//获取回复的评论信息
        if($info['pid'] == '0'){
            $mailTitle  = '留言板';
            $mailUrl    = $config['microblog'].'/Contact.html#comment-'.$info['id'].'';
        }else{
            $mailTitle = NewsModel::where('id',$info['pid'])->value('title');
            $mailUrl    = $config['microblog'].UrlModel::getShowUrl($info['pid']).'.html#comment-'.$info['id'].'';
        }
        
        $toemail = $info['mail'];//收件人邮箱
        $mail = new PHPMailer();
        $mail->isSMTP();// 使用SMTP服务
        $mail->CharSet = $config['CharSet'];// 编码格式为utf8
        $mail->Host = $config['Host'];// 发件人 的SMTP服务器地址
        $mail->SMTPAuth = true;// 是否使用身份验证
        $mail->isHTML(true);//支持Html代码
        $mail->Username = $config['Username'];// 发件人 的邮箱用户名，
        $mail->Password = $config['Password'];//发件人 客户端的16位授权密码,而不是邮箱的登录密码！
        $mail->SMTPSecure = $config['SMTPSecure'];// 使用ssl协议方式
        $mail->Port = $config['Port'];// 协议端口号 
        $mail->setFrom($config['Username'],"{$config['system_name']}-系统邮箱");//发件人信息 发件人邮箱-发件人名称
        $mail->addAddress($toemail,$info['nickname']);//收件人信息 收件人地址-收件人昵称
        $mail->addReplyTo($config['email'],"站长邮箱");//收件人收到邮件后，如需要回复，回复邮件将要发送到的邮箱地址
        $mail->Subject = "你在【{$config['system_name']}】发表的评论收到了回复";// 邮件标题
        $mail->Body = '<style>#p-mail-notify{font-size:14px;border:1px solid #dddddd;border-radius:10px;font-family:-apple-system,BlinkMacSystemFont,Roboto,Oxygen,Ubuntu,Cantarell,sans-serif;}#p-mail-notify a{display:inline-block;text-decoration:none;transition:all .3s;}#p-mail-notify a:hover{padding:0 5px;}#p-mail-notify .header,#p-mail-notify .footer{background-color:#007bff;padding:15px;color:#fff;}#p-mail-notify .header{border-top-left-radius:10px;border-top-right-radius:10px;}#p-mail-notify .header a{color:#ffcc33;}#p-mail-notify .main .tips a{color:#007bff;}#p-mail-notify .footer{font-size:12px;background-color:#8f969c;border-bottom-left-radius:10px;border-bottom-right-radius:10px;}#p-mail-notify .main{padding:15px;}#p-mail-notify .main .content-item{padding:10px;background-color:#343a40;border-radius:5px;color:#fff;margin:10px 0;}#p-mail-notify .main .tips{font-size:12px;color:#343a40;}</style>
            <div id="p-mail-notify">
                <div class="header">
                    '.$info['nickname'].' 你好，你在沛霖主页的<a href="'.$mailUrl.'" target="_blank">《'.$mailTitle.'》</a>文章中的评论有了新的回复：
                </div>
                <div class="main">
                    你的评论内容为：
                    <div class="content-item me">'.$info['content'].'</div>
                    你收到站长“'.$config['linkman'].'”对你的回复为：
                    <div class="content-item">'.$mailContact.'</div>
                    <div class="tips">
                        你也可以<a target="_blank" href="'.$mailUrl.'">直接点我进入原文章</a>以查看评论~
                    </div>
                </div>
                <div class="footer">
                    <span>本邮件为 '.$config['system_name'].' 自动发送，请勿直接回复<br />版权所有 盗版必究 本站任何文章转载均需要文章地址+评论</span>
                </div>
            </div>';// 邮件正文内容
        if(!$mail->send()){// 发送邮件
            return json(['code'=>0, 'msg'=>$mail->ErrorInfo]);
        }
    }

    public function add(){
        $admin_id = Session::get('admin_id');
        if(empty($admin_id)){
            return json(['code'=>1, 'msg'=>'请先登录','data'=>[]]);
        }
        $config = SettingModel::where('group','zh')->column('value','name');
        $Messmail_ss = $config['system_mail_hh'];     //查询邮件通知功能是否关闭
        $data = $this->request->param('data');
        $ip = get_client_ip();
        $auth = new DingdingModel();
        
        //获取用户系统、浏览器版本信息
        $agent = $_SERVER['HTTP_USER_AGENT'];
        $useragent = UserAgent_C::analyze($agent);
        //将该信息拆分存储
        $ptitle = $useragent->platform['title'];
        $pimage = $useragent->platform['image'];
        $btitle = $useragent->browser['title'];
        $bimage = $useragent->browser['image'];
        //存储该信息 前端转换
        $agentAll = '[faimg]../static/'.$pimage.'[/faimg]&nbsp;'.$ptitle.'&nbsp;&nbsp;[faimg]../static/'.$bimage.'[/faimg]'.$btitle;
        
        //获取IP地址的真实物理地址
        $con = file_get_contents('https://apis.map.qq.com/ws/location/v1/ip?key=xxxxx&ip='.$ip);
	    $json = json_decode($con,true);
		if($json['status'] == 0){
            $ipdz = $json['result']['ad_info']['nation'].$json['result']['ad_info']['province'].$json['result']['ad_info']['city'].$json['result']['ad_info']['district'];
		} else {
            $ipdz = "未获取到地址,你可能住在火星";
		}
		//确认传入参数种是否存在ID
        if(!empty($data['id'])){
            MessagesModel::update($data);
            $Dingmsg = '评论编辑成功，操作IP：'.$ip.'';
            $str = $auth->dingding_up($Dingmsg);
            return json(['code'=>0,'msg'=>'编辑成功']);
        }else{
            unset($data['id']);
            $data['avatar']     = '/storage/images/portrait.jpg';
            $data['messip']     = $ip;
            $data['ipmess']     = $ipdz;
            $data['useragent']  = $agentAll;
            MessagesModel::create($data);
            $mailId = $data['pcode'];
            $mailContact = $data['content'];
            if($Messmail_ss == 'on'){
                $this->e_mail($mailId,$mailContact);
            }
            $Dingmsg = '评论回复成功，操作IP：'.$ip.'';
            $str = $auth->dingding_up($Dingmsg);
            return json(['code'=>0,'msg'=>'评论回复成功']);
        }
    }
    
    // 管理留言
    public function editShu() {
        $admin_id = Session::get('admin_id');
        if(empty($admin_id)){
            return json(['code'=>1, 'msg'=>'请先登录','data'=>[]]);
        }
        
        $admin_id = Session::get('admin_id');
        $info = Session::get('adminInfo');
        $data = $this->request->param('data');
        $ip = get_client_ip();
        $auth = new DingdingModel();
        if(empty($admin_id)){
            return json(['code'=>1, 'msg'=>'非法请求']);
        }

        $userList = MessagesModel::order('create_time DESC')->select();
        if ($this->request->isPost()) {
            $id         = input('post.id');
            $value      = input('post.value');
            $action     = input('post.action');
            $status     = input('post.status');
            $category   = input('post.category');
            if($value == 'true'){
                $value = '1';
            }elseif($value == 'false'){
                $value = '0';
            }
            // 更新留言信息
            if($category == 'status'){
                if($value == '1'){
                    $Dingmsg = '评论显示，操作IP：'.$ip.'';
                }else{
                    $Dingmsg = '评论隐藏显示，操作IP：'.$ip.'';
                }
               MessagesModel::where('id', $id)->update([$status => $value]);
            }else{
                $Dingmsg = '评论更新成功，操作IP：'.$ip.'';
                MessagesModel::update([$category => $value,'id'=>$id]);
            }
            
            $str = $auth->dingding_up($Dingmsg);
            return json(['code'=>0,'msg'=>'操作成功']);
        }
        $this->getSide();
        return $this->fetch();
    }

    //获取文章标题
    public function getCategoryList(){
        $admin_id = Session::get('admin_id');
        if(empty($admin_id)){
            return json(['code'=>1, 'msg'=>'请先登录','data'=>[]]);
        }
        $lang = input('lang');
        // $NewsCategory =  new NewsCategoryModel();
        $NewsTitle = NewsModel::where(['status'=>'1'])->order('id', 'desc')->select();
        
        foreach ($NewsTitle as $key=>$val){
			if($lang=='en'){
				$NewsTitle[$key]['name'] = $val['title'];
			}
        }
        return json(['code'=>0,'msg'=>'操作成功','data'=>$NewsTitle]);
    }
    
}